<?php
/**
 * 服务器返回
 *
 */

require_once 'Common/DB.php';

$id=intval($_GET['id']);


$ret=$_POST;
$fp1=fopen('log.txt', 'a+');


$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();

foreach ($raw_post_array as $keyval)
{
	$keyval = explode ('=', $keyval);
	if (count($keyval) == 2)
	$myPost[$keyval[0]] = urldecode($keyval[1]);
}



$req = 'cmd=_notify-validate';

foreach ($myPost as $key => $value)
{
	$value = urlencode(stripslashes($value));
	$req .= "&$key=$value";
}
fwrite($fp1, serialize($req));
// Post back to PayPal to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

if (!$fp)
{
	//do something error handle


} else
{
	// NO HTTP ERROR

	fputs ($fp, $header . $req);
	$db = DbCon::getInstance();
	$con = $db->getCon();
		
	while (!feof($fp))
	{
		$res = fgets ($fp, 1024);
		if (strcmp ($res, "VERIFIED") == 0)
		{
			if($ret['transaction_type'] == 'Adaptive Payment PAY')
			{

				if($ret['status']=='COMPLETED')
				{
					$status='COMPLETED';
				}
				else if($ret['status'] == 'CREATED')
				{
					$status='CREATED';
				}
				/*else if($ret['status'] == 'PROCESSING')
				 {
					$status='PROCESSING';
					}
					else if($ret['status'] == 'PENDING')
					{
					$status='PENDING';
					}*/
				else
				{
					break;
				}
			}
			else if($ret['transaction_type'] == 'Adaptive Payment PREAPPROVAL')
			{
				if($ret['approved'] == 'true')
				{
					if($ret['status'] == 'CANCELED')
					{
						//取消

						$sql_del="delete from `order` where `key`='".$ret['preapproval_key']."'";
							
						$cancel=mysql_query($sql_del);
						if (!$cancel)
						{
							fwrite($fp1,$sql_del.'Invalid query: ' . mysql_error());
						}
						break;
					}
					else if($ret['status'] == 'ACTIVE')
					{
						$status='ACTIVE';
					}
					else
					{
						break;
					}
						
						
				}
				else
				{
					//删除？
					$sq_del="delete from tmp where id=".$id." limit 1";

					$rs=mysql_query($sq_del,$con);
					if (!rs)
					{
						fwrite($sql_del.' Invalid1 query: ' . mysql_error());
					}
					break;
				}

			}
			else
			{
				break;
			}
				
				
			$sql="select * from tmp where id=".$id;
			$rs=mysql_query($sql,$con);			
			$row = mysql_fetch_array($rs);

			if($_POST['pay_key'] && $row['key'] == $ret['pay_key'])
			{
				$sql_insert="insert into `order` set pid=1,`type`=2,add_time=now(),address='".$row['address']."'";
				$sql_insert.=",email='".$row['email']."'";
				$sql_insert.=",fname='".$row['fname']."'";
				$sql_insert.=",lname='".$row['lname']."'";
				$sql_insert.=",`key`='".$row['key']."'";
				$sql_insert.=",status='".$status."'";
			}
			else if($_POST['preapproval_key'] && $row['key'] == $ret['preapproval_key'])
			{
				$sql_insert="insert into `order` set pid=1,`type`=1,add_time=now(),address='".$row['address']."'";
				$sql_insert.=",email='".$row['email']."'";
				$sql_insert.=",fname='".$row['fname']."'";
				$sql_insert.=",lname='".$row['lname']."'";
				$sql_insert.=",`key`='".$row['key']."'";
				$sql_insert.=",status='".$status."'";
			}
			else
			{
				break;
			}
				
			//插入order表 同时删除tmp表里面的记录
			$rs=mysql_query($sql_insert,$con);
			fwrite($fp1, serialize('insert==='.$sql_insert));
			fwrite($fp1, "\n\r");
			$sq_del="delete from tmp where id=".$id." limit 1";
			$del=mysql_query($sq_del,$con);
				
				
		}
		else if (strcmp ($res, "INVALID") == 0)
		{
			// If 'INVALID', send an email. TODO: Log for manual investigation.
			//零时表记录删除掉
			$sq_del="delete from tmp where id=".$id." limit 1";
			$rs=mysql_query($sq_del,$con);				
			break;				
		}
	}
}
$db->closeDB();
fclose ($fp);
fclose($fp1);